#include"Selector.h"

Selector::Selector()
{
	FD_ZERO(&m_readset);
	FD_ZERO(&m_writeset);	
	FD_ZERO(&m_exceptionset);
}

void Selector::Register(SOCKET socket)
{
	m_sockets.push_back(socket);
}

void Selector::UnRegister(SOCKET socket)
{
	std::vector<SOCKET>::iterator it = m_sockets.begin();
	for(;it!=m_sockets.end();++it)
	{
		if(*it == socket)
		{
			break;
		}
	}

	if(it!=m_sockets.end())
		m_sockets.erase(it);
}

bool Selector::CanRead(SOCKET socket)
{
	return FD_ISSET(socket,&m_readset) > 0;
}

bool Selector::CanWrite(SOCKET socket)
{
	return FD_ISSET(socket,&m_writeset) > 0;
}

bool Selector::IsException(SOCKET socket)
{
	return FD_ISSET(socket,&m_exceptionset) > 0;	
}

bool Selector::Poll(int millsecond)
{
	struct timeval tm;
	tm.tv_sec = 0;
	tm.tv_usec = millsecond;

	FD_ZERO(&m_readset);
	FD_ZERO(&m_writeset);
	FD_ZERO(&m_exceptionset);

	std::vector<SOCKET>::size_type count = m_sockets.size();
	for(std::vector<SOCKET>::size_type i = 0; i < count; ++i)
	{
		SOCKET st = m_sockets[i];
		FD_SET(st,&m_readset);
		FD_SET(st,&m_writeset);
		FD_SET(st,&m_exceptionset);
	}

	bool ret = ::select(100,&m_readset,&m_writeset,&m_exceptionset,&tm)>0;
	if(ret)
	{
		return true;
	}
	else
	{
		int error = GetLastError();
		return false;
	}
}

